

var file_name = 'n_storage';
var storage = storages.create("wudi");
var storage_name = storage.get('storage_name')
if (storage_name) {
    file_name = storage_name;
}
try {
    var statusBarHeight = getStatusBarHeight(); //0
    var highestViewId = 0
    var region = null //floatyWindow选择时并绘制边框
    var allAttributes = null //查看控件信息
    var uiObjects = findViewNodesByDFS(auto.rootInActiveWindow) //最初获取全部控件属性

    var data = convertArray(uiObjects); // log(JSON.stringify(data))//在布局层次中查看的数据
} catch (e) {
    toastLog("无障碍未开启");
}

function getStatusBarHeight() {
    var resources = context.getResources();
    var resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
    var statusBarHeight = resources.getDimensionPixelSize(resourceId);
    return statusBarHeight;
}


ui.run(() => {
    var popupWindow = null; // 保存弹窗菜单的变量
    var drawFloaty = floaty.rawWindow(
        <canvas id="board" />
    )
    drawFloaty.setSize(-1, -1);
    drawFloaty.board.setOnTouchListener(function (view, event) {
        switch (event.getAction()) {
            case event.ACTION_UP:
                downX = parseInt(event.getX());
                downY = parseInt(event.getY());
                // 根据条件筛选UI对象
                allAttributes = uiObjects.filter(function (obj) {
                    var bounds = obj.viewNode.bounds();
                    return bounds.contains(downX, downY + statusBarHeight); // 加上状态栏高度后再进行包含判断
                }).sort(function (a, b) {
                    var boundsA = a.viewNode.bounds();
                    var boundsB = b.viewNode.bounds();
                    return boundsB.width() * boundsB.height() - boundsA.width() * boundsA.height();
                }).pop();
                // log(allAttributes)
                return true;
            case event.ACTION_DOWN:
                downX = parseInt(event.getX());
                downY = parseInt(event.getY());

                //可查看布局分析
                var popView = ui.inflate(
                    <vertical margin="0 5">
                        <card cardCornerRadius="5dp" cardElevation="5" >
                            <vertical animateLayoutChanges="true" gravity="center" >
                                <card backgroundTint="#FF333333" gravity="center" cardCornerRadius="0dp" margin="0" >
                                    <button h="40" id="查看控件信息" textSize="12sp" text="查看控件信息" textColor="#FF00FF00" textStyle="bold" style="Widget.AppCompat.Button.Borderless" />
                                </card>
                                <card backgroundTint="#FF333333" gravity="center" cardCornerRadius="0dp" margin="0" >
                                    <button h="40" id="查看布局层次" textSize="12sp" text="在布局层次中查看" textColor="#FF00FF00" textStyle="bold" style="Widget.AppCompat.Button.Borderless" />
                                </card>
                                <card backgroundTint="#FF333333" gravity="center" cardCornerRadius="0dp" margin="0" >
                                    <button h="40" id="退出" textSize="12sp" text="退出布局分析" textColor="#FF00FF00" textStyle="bold" style="Widget.AppCompat.Button.Borderless" />
                                </card>
                            </vertical>
                        </card>
                    </vertical>, null, false);
                if (popupWindow != null) {
                    popupWindow.dismiss(); // 关闭之前的弹窗菜单
                    popupWindow = null; // 重置弹窗菜单变量
                }


                // 创建新的弹窗菜单
                popupWindow = new android.widget.PopupWindow(popView, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setFocusable(true); //设置下拉菜单可以被关闭
                popupWindow.setBackgroundDrawable(function () {
                    var d = new android.graphics.drawable.GradientDrawable();
                    d.setColor(colors.parseColor("#FF333333"));
                    d.setCornerRadius(20);
                    return d;
                }());

                // 根据条件筛选UI对象
                allAttributes = uiObjects.filter(function (obj) {
                    var bounds = obj.viewNode.bounds();
                    return bounds.contains(downX, downY + statusBarHeight); // 加上状态栏高度后再进行包含判断
                }).sort(function (a, b) {
                    var boundsA = a.viewNode.bounds();
                    var boundsB = b.viewNode.bounds();
                    return boundsB.width() * boundsB.height() - boundsA.width() * boundsA.height();
                }).pop();
                var node = allAttributes.viewNode;
                if (node) {
                    var region = [
                        node.bounds().left,
                        node.bounds().top - statusBarHeight,
                        node.bounds().right,
                        node.bounds().bottom - statusBarHeight
                    ];
                }

                // 根据坐标显示PopupWindow
                popupWindow.showAtLocation(view, android.view.Gravity.LEFT | android.view.Gravity.TOP, region[0], region[3] + 10);
                popupWindow.setOutsideTouchable(true);

                popView.查看控件信息.on("click", () => {
                    查看控件信息(allAttributes.viewNode)
                })
                popView.查看布局层次.on("click", () => {
                    popupWindow.dismiss();
                    查看布局层次(data)
                    drawFloaty.board.attr("visibility", "gone") //invisible//visible
                })
                popView.退出.on("click", () => {
                    exit()
                })
                return true;
        };
        return true;
    })

    drawFloaty.board.on("draw", function (canvas) {
        var paint = new Paint();
        paint.setFakeBoldText(true);
        canvas.drawColor(0, android.graphics.PorterDuff.Mode.CLEAR); // 清理画布
        canvas.drawARGB(180, 24, 24, 24); // 绘制背景颜色

        uiObjects.forEach(function (obj) {
            var node = obj.viewNode;
            var region = [
                node.bounds().left,
                node.bounds().top - statusBarHeight,
                node.bounds().right,
                node.bounds().bottom - statusBarHeight
            ];
            paint.setStrokeWidth(2);
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(colors.parseColor("#FF00FF00")); //FF963200
            canvas.drawRect.apply(canvas, region.concat(paint));
        });

        if (allAttributes) {
            var node = allAttributes.viewNode;
            var region = [
                node.bounds().left,
                node.bounds().top - statusBarHeight,
                node.bounds().right,
                node.bounds().bottom - statusBarHeight
            ];
            // 绘制选中区域的描边颜色
            paint.setStrokeWidth(0);
            paint.setStyle(Paint.Style.FILL_AND_STROKE)
            //paint.setColor(colors.parseColor("#70ffffff"))
            //colors.setPaintColor(paint, "#70ffffff");
            paint.setARGB(125, 255, 255, 255);
            canvas.drawRect.apply(canvas, region.concat(paint));
            // 设置选中区域的填充底颜色
            paint.setStrokeWidth(2);
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(colors.parseColor("#ff0000"))
            canvas.drawRect.apply(canvas, region.concat(paint));
        }
    });
    optimizeFloaty(drawFloaty); //监听悬浮窗返回键
    setInterval(new Function, 1e3);
})



/* -------------------------------------------------------------------------- */

function 查看布局层次(data) {
    ui.run(() => {
        var floatyFrame = floaty.rawWindow(
            <HorizontalScrollView id="container" fillViewport="true" bg="#ffffff" alpha="0.8">
                <ScrollView>

                    <vertical id="scrollContent"  >
                    </vertical>
                </ScrollView>
            </HorizontalScrollView>
        );

        var myView = new getMyView(data, true); // 初始展开根节点
        //     // 计算并滚动以确保最后一个项目可见

        ui.run(function () {
            floatyFrame.setSize(-1, -1);
            floatyFrame["container"].scrollContent.addView(myView.view);
        });
        optimizeFloaty(floatyFrame);
        setInterval(new Function, 1e3);

        var floatyWindow = floaty.rawWindow(
            <vertical>
                <canvas id="place" />
            </vertical>
        );

        ui.run(() => {
            floatyWindow.setTouchable(false);
            floatyWindow.setSize(-1, -1);
        });

        floatyWindow.place.on("draw", function (canvas) {
            var paintGreen = new Paint();
            paintGreen.setFakeBoldText(true);
            paintGreen.setStrokeWidth(4);
            paintGreen.setStyle(Paint.Style.STROKE);
            paintGreen.setColor(colors.parseColor("#ff0000"));
            canvas.drawColor(0, android.graphics.PorterDuff.Mode.CLEAR);
            var rect;
            if (region) {
                rect = [
                    region.bounds().left,
                    region.bounds().top - statusBarHeight,
                    region.bounds().right,
                    region.bounds().bottom - statusBarHeight
                ];
            } else if (allAttributes) {
                region = allAttributes.viewNode;
                rect = [
                    region.bounds().left,
                    region.bounds().top - statusBarHeight,
                    region.bounds().right,
                    region.bounds().bottom - statusBarHeight
                ];
            }

            if (rect) {
                canvas.drawRect.apply(canvas, rect.concat(paintGreen));
            }
        });
    })
}

//未完成定位部分

function getMyView(data, expanded) {
    this.view = ui.inflate(
        <vertical>
            <card gravity="center||left" cardCornerRadius="0dp" cardElevation="0dp" cardBackgroundColor="#ffffff" foreground="?attr/selectableItemBackground" >
                <linear gravity="center||left" >
                    <img id="iconIng" w="23" h="32" tint="#FFFFFF" src="@drawable/ic_keyboard_arrow_down_black_48dp" />
                    <text gravity="center||left" h="32" id="name" textSize="15" layout_weight="1" foreground="?attr/selectableItemBackground" />
                </linear>
                <vertical h="2px" bg="#20000000" />
            </card>
            <vertical id="vt_2" marginLeft="20" />
        </vertical>
    );
    var childViews = null;
    this.updateView = function (data, expanded) {
        if (!Array.isArray(data) || data.length === 0) {
            return null;
        }
        var iconIngView = this.view.iconIng;
        var nameTextView = this.view.name;
        var vt2Layout = this.view.vt_2;

        iconIngView.removeAllListeners(); // 先移除所有事件监听器
        nameTextView.removeAllListeners(); // 先移除所有事件监听器
        //获取数据进行处理
        var genus = data[0].text;
        var controlAttributes = getControlAttributes(genus);
        // 更新名称和图标
        nameTextView.setText(controlAttributes);

        if (data[0].children.length == 0) {
            //nameTextView.setText("▶ " + controlAttributes)
            nameTextView.attr("textColor", "#ff0000");
            iconIngView.attr("tint", "#ff0000");
            iconIngView.attr("src", "@drawable/ic_keyboard_arrow_right_black_48dp");

        } else if (expanded) {
            //nameTextView.setText("▼ " + controlAttributes)
            nameTextView.attr("textColor", "#000000");
            iconIngView.attr("tint", "#000000");
            iconIngView.attr("src", "@drawable/ic_keyboard_arrow_down_black_48dp");
        } else {
            //nameTextView.setText("▶ " + controlAttributes)
            nameTextView.attr("textColor", "#FF6DB224");
            iconIngView.attr("tint", "#FF6DB224");
            iconIngView.attr("src", "@drawable/ic_keyboard_arrow_right_black_48dp");
        }

        // 清空视图布局中的所有子视图
        vt2Layout.removeAllViews();
        // 检查展开状态（expanded）

        // 全局缓存对象
        var viewCache = {};
        // 从缓存中获取视图
        function getViewFromCache(data) {
            return viewCache[data.id];
        }
        // 将视图添加到缓存中
        function addToCache(view, data) {
            viewCache[data.id] = view;
        }

        if (expanded) {
            threads.start(new java.lang.Runnable(() => {
                // 创建子视图数组
                var childViews = [];
                var children = data[0].children;
                for (var i = 0; i < children.length; i++) {
                    var child = children[i];
                    var childView = getViewFromCache(child);
                    if (!childView) {
                        // 创建子视图
                        childView = new getMyView([child], true);
                        // 将子视图添加到缓存中
                        addToCache(childView, child);
                    }
                    childViews.push(childView);
                }
                // 在UI线程中批量添加子视图
                ui.post(() => {
                    for (var i = 0; i < childViews.length; i++) {
                        var childView = childViews[i];
                        vt2Layout.addView(childView.view);
                    }
                });
            }));
        }

        nameTextView.click(() => {
            region = genus
            var currentViewId = data[0].id; // 获取数据中的第一个视图的 ID
            // 检查当前视图的 ID 是否大于最高视图 ID
            if (currentViewId > highestViewId) {
                highestViewId = currentViewId; // 如果是，更新最高视图 ID
            } else {
                highestViewId = currentViewId; // 否则，将最高视图 ID 设置为当前视图 ID
                expanded = !expanded; // 切换展开和折叠状态
                this.updateView(data, expanded); // 调用 updateView 方法，传递数据和新的展开/折叠状态
            }
        });
        nameTextView.on("long_click", (event) => {
            查看控件信息(genus)
            event.consumed = true;
        });
    };

    this.updateView(data, expanded);
    return this;
};






function getControlAttributes(genus) {
    var control = [
        genus.text(),
        genus.desc(),
        genus.id(),
        genus.className(),
        genus.clickable()
    ];
    var attributes = [];
    var str;
    if (control[0]) attributes.push("text=" + control[0]);
    if (control[1]) attributes.push("desc=" + control[1]);
    if (control[2]) {
        str = control[2];
        var match = str.match(/:id\/(.*)/);
        str = match ? match[1] : str;
        attributes.push("id=" + str);
    }
    if (control[3]) {
        str = control[3];
        var match = str.match(/android\.widget\.(.*)/);
        str = match ? match[1] : str;
    }
    if (control[4]) {
        attributes.push("clickable=" + control[4]);
    }
    var parentView = attributes.length > 0 ? " [" + attributes.join(",") + "]" : "";
    var isadd = str + parentView;
    return isadd;
}

// if (expanded) {
//     threads.start(new java.lang.Runnable(() => {
//         var childViews = [];
//         var children = data[0].children;
//         for (var i = 0; i < children.length; i++) {
//             var child = children[i];
//             var childView = new getMyView([child], true);
//             childViews.push(childView);
//         }
//         ui.run(function() {
//             for (var i = 0; i < childViews.length; i++) {
//                 var childView = childViews[i];
//                 vt2Layout.addView(childView.view);
//             }
//         });
//     }));
// };



/* 查看控件信息-------------------------------------------------------------------------- */
let n = ""

// 用于模拟文件系统相关操作的对象（这里只是简单模拟，实际需替换为对应环境下真实可用的文件操作模块）
function readFromFile() {
    var filePath = "/sdcard/" + file_name + ".js";
    if (files.exists(filePath)) {
        return files.read(filePath, "utf8");
    }
    return "";  // 如果文件不存在返回空字符串
}

function saveToFile(content) {
    var filePath = "/sdcard/" + file_name + ".js";
    var existingContent = readFromFile();  // 调用已有的读取函数获取原内容

    let beforeWhilePart = "";
    let insideWhilePart = "";
    let afterWhilePart = "";

    // 判断是否已经存在while(true)代码块
    let hasWhileTrueBlock = existingContent.includes('while(true) {');
    if (hasWhileTrueBlock) {
        // 获取while(true)代码块起始和结束位置，提取其内部内容
        let startIndex = existingContent.indexOf('while(true) {');
        let endIndex = existingContent.lastIndexOf('}');
        beforeWhilePart = existingContent.substring(0, startIndex);
        insideWhilePart = existingContent.substring(startIndex + 'while(true) {'.length, endIndex).trim();
        afterWhilePart = existingContent.substring(endIndex + 1);

        // 删除原有的while(true)代码块结构，只保留内部内容
        existingContent = beforeWhilePart + insideWhilePart + afterWhilePart;
    }

    // 将新传入的内容添加到while(true)内部内容中（处理换行等格式）
    insideWhilePart = (insideWhilePart ? insideWhilePart + "\n" : "") + content + "\n";
    // 重新构建包含while(true)的完整内容并写入文件
    let combinedContent = beforeWhilePart + "\n" + insideWhilePart + "\n" + afterWhilePart;
    files.write(filePath, combinedContent, "utf8");
}

function createInitialFileIfNotExists() {
    var filePath = "/sdcard/" + file_name + ".js";
    if (!files.exists(filePath)) {
        var initialContent = `function 模拟点击(uiObject) {
            if (uiObject) {
                // 获取控件的bounds属性，它返回一个包含left、top、right、bottom四个值的对象
                var boundsInfo = uiObject.bounds();
                // 计算bounds的中心坐标，以便点击控件的大致中心位置
                var x = (boundsInfo.left + boundsInfo.right) / 2;
                var y = (boundsInfo.top + boundsInfo.bottom) / 2;
                click(x, y);
            } else {
                toast("传入的UiObject为空，无法进行点击操作");
            }
        } while(true) {
        }`;
        files.write(filePath, initialContent, "utf8");
    }
}

createInitialFileIfNotExists();
// 示例调用，这里假设要添加一句log输出语句到while(true)里面

function 查看控件信息(uiObj) {
    var Attribute = [
        "accessibilityFocused", "bounds", "checked", "className", "clickable", "column", "columnCount", "columnSpan", "depth", "desc", "drawingOrder", "enabled", "id", "indexInParent", "longClickable", "packageName", "row", "rowCount", "rowSpan", "scrollable", "selected", "text", "visibleToUser",
    ]
    //获取筛选后的控件属性
    let newObj = {};
    for (let key in Attribute) {
        newObj[key] = Attribute[key];
    };
    var items = Object.keys(newObj).map(i => ({
        属性: newObj[i],
        值: newObj[i] === "bounds" ? uiObj.bounds().toString() : uiObj[newObj[i]](),
        checked: true
    }));

    let Generateid = ui.inflate(
        <vertical id="parent">
            {/*属性*/}
            <vertical>
                <horizontal orientation="horizontal" gravity="center">
                    <text margin="5 10" gravity="center" text="属性" textSize="12sp" color="#000000" layout_weight="1" w="0" />
                    <text margin="5 10" gravity="center" text="值" textSize="12sp" color="#000000" layout_weight="1" w="0" />
                </horizontal>
                <grid id="list" h="500" >
                    <card margin="0 1" h="auto" cardElevation="1dp" cardBackgroundColor="#FFE9EDDF">
                        <horizontal orientation="horizontal" gravity="center" >
                            <checkbox id="checkbox" checked="{{this.checked}}" scaleY="0.9" scaleX="0.9" />
                            <card id="属性" gravity="center" h="*" cardElevation="0dp" cardBackgroundColor="#FFE9EDDF" layout_weight="1" w="0" foreground="?attr/selectableItemBackground" clickable="true" >
                                <text text="{{this.属性}}" textSize="13sp" gravity="center" />
                            </card>
                            <card id="值" gravity="center" h="*" cardElevation="0dp" cardBackgroundColor="#FFE9EDDF" layout_weight="2" w="0" foreground="?attr/selectableItemBackground" clickable="true">
                                <text text="{{this.值}}" textSize="13sp" gravity="center" maxLines="2" ellipsize="middle" />
                            </card>
                        </horizontal>
                    </card>
                </grid>
            </vertical>
            {/*生成*/}
        </vertical>, null, false
    );

    Generateid.list.setDataSource(items);
    Generateid.list.on("item_bind", function (itemView, itemHolder) {
        itemView.checkbox.setOnCheckedChangeListener((view, checked) => {
            if (!view.isPressed()) return;
            itemHolder.item.checked = checked;
        });
        itemView.属性.on("click", function () {
            let item = itemHolder.item.属性;
            console.log(item);
            setClip(item);
        });
        itemView.值.on("click", function () {
            let item = itemHolder.item.值;
            console.log(item);
            setClip(item);
        });
        itemView.值.on("long_click", params => {
            params.consumed = true;
            log(itemHolder.item.属性 + " : " + itemHolder.item.值);
            setClip(itemHolder.item.属性 + " : " + itemHolder.item.值);
        });

    });

    //$dialogs.setDefaultDialogType("foreground-or-overlay");
    let dialog = dialogs.build({
        type: "overlay",
        customView: Generateid,
        negative: "添加节点到配置",

        neutral: "取消",
        negativeColor: "#FF3E6528",

        neutralColor: "#FF3E6528",
        //  autoDismiss: false,
        wrapInScrollView: false
    }).on("negative", () => {
        let result = "";
        items.forEach(value => {
            if (value.checked) {
                if (value.属性 === "bounds") {
                    let boundsValue = value.值;
                    // 增加对null值或空值的判断，若为空则直接跳过，不进行后续处理和拼接操作
                    if (!boundsValue) {
                        return;
                    }
                    // 如果是字符串类型，进行格式处理
                    if (typeof boundsValue === "string") {
                        // 去除Rect字样（假设存在）并去除两端空白字符
                        boundsValue = boundsValue.replace(/Rect/g, "").trim();
                        // 使用正则表达式转换格式，确保格式准确匹配（这里修正了正则表达式中多余的空格问题）
                        boundsValue = boundsValue.replace(/(\d+), (\d+) - (\d+), (\d+)/, ($0, $1, $2, $3, $4) => {
                            return `${$1},${$2},${$3},${$4}`;
                        });
                    }
                    // 直接拼接处理后的bounds值，不添加引号
                    result += `bounds${boundsValue}.`;
                } else {
                    // 非bounds属性按照原逻辑处理
                    let processedValue = (typeof value.值 === "string") ? value.值.replace("rect", "") : value.值;
                    // 增加对null值或空值的判断，若为空则直接跳过，不进行后续拼接操作
                    if (!processedValue) {
                        return;
                    }
                    if (typeof processedValue === "boolean" || typeof processedValue === "number") {
                        result += value.属性 + '(' + processedValue + ').';
                    } else {
                        result += value.属性 + '("' + processedValue + '").';
                    }
                }
            }
        });


        var generate = result.replace(/\.$/, "");
        // 获取当前时间戳并取后几位作为变化部分融入变量名
        let timestampPart = Date.now().toString().slice(-8); // 取时间戳的后4位
        let objectName = `wudi${timestampPart}`;
        var Copycode = `var ${objectName} = ${generate}.findOne(50);\nif (${objectName}) {\n模拟点击(${objectName})\nlog("${objectName}")\n};`;

        n += "" + Copycode;
        saveToFile(n);
        log(n)

    }).on("positive", () => {
        let selector = {};
        items.forEach(value => {
            if (value.checked) {
                selector[value.属性] = value.值;
            }
        });
        log('select(' + JSON.stringify(selector, null, 2) + ')');
    }).on("neutral", () => {
        exit()
    }).on("dismiss", () => {
        // exit();
    });
    dialog.show();
    //dialog.dismiss();
    let gradientDrawable = new android.graphics.drawable.GradientDrawable();
    gradientDrawable.setShape(android.graphics.drawable.GradientDrawable.RECTANGLE);
    gradientDrawable.setColor(colors.parseColor("#FFE9EDDF"));
    gradientDrawable.setCornerRadius(50);
    dialog.getWindow().setBackgroundDrawable(gradientDrawable);
    //dialog.setCancelable(false)
}



/* 这是DFS方式的递归, 通常递归都是dfs-------------------------------------------------------------------------- */

function findViewNodesByDFS(viewNode) {
    let viewNodes = []; // 节点入库  
    viewNodes.push(viewNode); // 遍历节点   
    let childCount = viewNode.childCount();
    for (let i = 0; i < childCount; i++) {
        let childViewNode = viewNode.child(i);
        let childViewNodes = findViewNodesByDFS(childViewNode);
        viewNodes = viewNodes.concat(childViewNodes);
    }
    return viewNodes;
}

function findViewNodesByDFS(viewNode, parentViewNodeObj, childViewNodeIndex) {
    let viewNodeObjs = [];
    let viewNodeObj = null;
    if (!parentViewNodeObj) {
        // 处理根节点       
        viewNodeObj = {
            viewNode: viewNode,
            _level: 0,
            _levelStr: "0",
            //_expand: false,
        };
        viewNodeObjs.push(viewNodeObj);
    } else { // 其他节点      
        viewNodeObj = {
            viewNode: viewNode,
            _level: parentViewNodeObj._level + 1,
            _levelStr: parentViewNodeObj._levelStr + "-" + childViewNodeIndex,
            // _expand: false,
        };
        viewNodeObjs.push(viewNodeObj);
    }
    let childCount = viewNode.childCount();
    if (childCount !== null) {
        for (let i = 0; i < childCount; i++) {
            let childViewNode = viewNode.child(i);
            let childViewNodes = findViewNodesByDFS(childViewNode, viewNodeObj, i);
            viewNodeObjs = viewNodeObjs.concat(childViewNodes);
        }
    } else {
        log("null")
    }
    return viewNodeObjs;
}


function convertArray(nodes) {
    var result = [];
    var stack = [];
    var currentLevel = -1;
    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        if (node._level > currentLevel) {
            var newNode = {
                id: i,
                text: node.viewNode,
                // expand: true,
                children: []
            };
            if (stack.length > 0) {
                stack[stack.length - 1].children.push(newNode);
            } else {
                result.push(newNode);
            }
            stack.push(newNode);
            currentLevel = node._level;
        } else if (node._level === currentLevel) {
            var newNode = {
                id: i,
                text: node.viewNode,
                // expand: false,
                children: []
            };
            stack.pop();
            stack.push(newNode);
            if (stack.length > 1) {
                stack[stack.length - 2].children.push(newNode);
            } else {
                result.push(newNode);
            }
        } else {
            while (stack.length > 0 && node._level <= currentLevel) {
                stack.pop();
                currentLevel--;
            }
            i--;
        }
    }
    return result;
}



//监听悬浮窗返回键

function optimizeFloaty(floatyObj) {
    let KeyEvent = android.view.KeyEvent;
    let floatyClass = floatyObj.getClass();
    let windowField = floatyClass.getDeclaredField("mWindow");
    windowField.setAccessible(true);
    let rootView = windowField.get(floatyObj).getWindowView();
    ui.run(() => {
        rootView.setOnKeyListener((view, keyCode, event) => {
            if (event.getAction() === KeyEvent.ACTION_UP && keyCode === KeyEvent.KEYCODE_BACK) {
                exit();
                return true;
            }
            return false;
        });
        floatyObj.requestFocus();
        rootView.setFocusable(true);
        rootView.setFocusableInTouchMode(true);
        rootView.requestFocus();
    });
}

events.setKeyInterceptionEnabled("volume_down", true);
threads.start(function () {
    events.observeKey(); //音量下键被按下了
    events.on("key", function (volume_down, event) {
        toast("控件已停止运行");
        exit();
    });
});

setInterval(() => { }, 1000)

limit()

function limit() {
     let bridge = runtime.accessibilityBridge;
     let bridgeField = runtime.getClass().getDeclaredField("accessibilityBridge");
     let configField = bridgeField.getType().getDeclaredField("mConfig");
     configField = configField.getType().newInstance()
     let arrayList = configField.getClass().getDeclaredFields()[0].toString()
     arrayList = arrayList[arrayList.length - 1]
     try {
         string = configField.getClass().getDeclaredFields()[2].toString()
     } catch (error) {
         string = configField.getClass().getDeclaredFields()[1].toString()
     }
     string = string[string.length - 1]
     configField.getClass().getDeclaredField(arrayList).get(configField[string]).clear()
     auto.setWindowFilter(function(window) {
         return window.active;
     });
 };
